<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数对象
      queryInfo: {
        // 查询关键字
        query: '',
        // 商品 id
        cid: '',
        // 页码值
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 10
      },
      // 商品列表数据
      goodsList: [],
      // 总数据调试
      total: 0,
      // 当前是否正在请求数据
      isloading: false
    }
  },
  onLoad(options) {
    this.queryInfo.query = options.query || ''
    this.queryInfo.cid = options.cid || ''
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表数据的方法
    async getGoodsList(isPull, cb) {
      // 打开节流阀
      this.isloading = true
      const { data: res } = await uni.$http.get('/goods/search', this.queryInfo)
      // 关闭节流阀
      this.isloading = false
      // 短路运算符调用 cb 函数
      cb && cb()
      if (res.meta.status !== 200) return uni.$showMsg()

      if (isPull) {
        this.goodsList = [...res.message.goods, ...this.goodsList]
      } else {
        this.goodsList = [...this.goodsList, ...res.message.goods]
      }

      this.goodsList = [...this.goodsList, ...res.message.goods]
      this.total = res.message.total
    },
    gotoDetail(goods) {
      uni.navigateTo({
        url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
      })
    }
  },
  onReachBottom() {
    if (this.queryInfo.pagenum * this.queryInfo.pagesize >= this.total)
      return uni.$showMsg('数据加载完毕！')

    if (this.isloading) return

    // 让页码值自增 +1
    this.queryInfo.pagenum++
    this.getGoodsList()
  },
  onPullDownRefresh() {
    if (this.queryInfo.pagenum * this.queryInfo.pagesize >= this.total) {
      uni.$showMsg('数据加载完毕！')
      uni.stopPullDownRefresh()
      return
    }

    if (this.isloading) return

    const isPull = true

    // 让页码值自增 +1
    this.queryInfo.pagenum++
    this.getGoodsList(isPull, () => uni.stopPullDownRefresh())
  }
}
</script>

<style lang="scss"></style>
